package com.gl.utils;

import org.bytedeco.ffmpeg.global.avcodec;
import org.bytedeco.javacv.*;

public class Mp4ToMp3 {

    /**
     * 将mp4文件转换为mp3文件
     * @param inputPath 输入的文件路径 mp4
     * @param outputPath 输出的文件路径 mp3
     */
    public static void convert(String inputPath, String outputPath) {
        FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(inputPath);
        FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(outputPath, 0); // 0表示纯音频

        try {
            grabber.start();
            // 关键配置：设置音频编码参数
            recorder.setAudioCodec(avcodec.AV_CODEC_ID_MP3);
            recorder.setAudioBitrate(128000); // 128kbps
            recorder.setAudioChannels(2);     // 立体声
            recorder.setSampleRate(44100);    // 采样率
            recorder.setFormat("mp3");        // 明确指定格式
            recorder.start();

            while (true) {
                Frame frame = grabber.grabFrame();
                if (frame == null) break;
                if (frame.samples != null) {
                    recorder.record(frame);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("mp4转化mp3失败！！！");
        } finally {
            try {
                grabber.stop();
                recorder.stop();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}